<template>
	<view class="edit-address">
        <uv-form labelPosition="left" :model="userInfo" :rules="rules" ref="form">
			<uv-form-item label="收货人" prop="realName" borderBottom labelWidth="72">
				<uv-input v-model="userInfo.realName" placeholder="请输入收货人名称" border="none">
				</uv-input>
			</uv-form-item>
            <uv-form-item label="联系电话" prop="mobile" borderBottom labelWidth="72">
				<uv-input v-model="userInfo.mobile" placeholder="请输入联系电话" border="none">
				</uv-input>
			</uv-form-item>
            <uv-form-item label="选择地区" prop="pickerValue" borderBottom labelWidth="72" @click="openChoose">
				<uv-input v-model="pickerText" border="none" placeholder="请选择" :readonly="true">
				</uv-input>
                <template v-slot:right>
					<uv-icon size="13" name="arrow-right"></uv-icon>
				</template>
			</uv-form-item>
            <uv-form-item label="详细地址" prop="address" borderBottom labelWidth="72">
				<uv-input v-model="userInfo.address" placeholder="请输入详细地址,门牌号" border="none">
				</uv-input>
			</uv-form-item>
            <uv-form-item label="设为默认地址" prop="defaultAddress" labelWidth="102">
				<template v-slot:right>
					<uv-switch v-model="userInfo.defaultAddress" activeValue="Y" inactiveValue="N"></uv-switch>
				</template>
			</uv-form-item>
			<uv-button type="primary" shape="circle" text="保存" customStyle="margin-top: 10px;position: fixed;bottom: 3%;width: 90%;left: 4%;" @click="submit"></uv-button>
		</uv-form>
        <uv-picker ref="picker" :columns="addressList" :loading="loading" keyName="name" @change="change" @confirm="confirmChange">
		</uv-picker>
	</view>
</template>
<script setup lang="ts">
import { ref , getCurrentInstance , withDefaults,computed,onMounted,defineExpose} from 'vue'
import { province , citys , countys } from '@/api/baseData'
import { onLoad } from "@dcloudio/uni-app"
import { getAddress , saveAddress} from '@/api/product'
const userInfo = ref<any>({
    addressId:'',
    realName:'',
    mobile:'',
    pickerValue:[],
    address:'',
    citycode:'',
    countycode:'',
    provincecode:'',
    defaultAddress:"Y"
})
const pickerText = ref<any>('')
const rules = ref<any>({
    'realName': {
        type: 'string',
        required: true,
        message: '请填写姓名',
        trigger: ['blur', 'change']
    },
    'mobile': {
        type: 'string',
        required: true,
        message: '请填写联系电话',
        trigger: ['blur', 'change']
    },
    'address': {
        type: 'string',
        required: true,
        message: '请填写详细地址',
        trigger: ['blur', 'change']
    },
})
const picker = ref()
const provinces = ref<any>([])//省
const citys = ref<any>([])//省
const areas = ref<any>([])//省
const loading = ref<any>(false)
const defaultValue = ref<any>([11, 110100, 19])
const addressList = computed(() => {
    return [provinces.value, citys.value, areas.value];
})

const change = (e : any) => {
    if (loading.value) return;
    const { columnIndex, index, indexs } = e
    // 改变了省
    if (columnIndex === 0) {
        citys.value = provinces.value[index]?.cityList || []
        areas.value = citys.value[0]?.countyList || []
        picker.value.setIndexs([index, 0, 0],true)
    } else if (columnIndex === 1) {
        areas.value = citys.value[index]?.countyList || []
        picker.value.setIndexs(indexs,true)
    }
}
const handlePickValueDefault = () => {
    const _pickerValue = []
    // 设置省
    _pickerValue[0] = provinces.value.findIndex(item => Number(item.provincecode) === defaultValue.value[0]);
    // 设置市
    citys.value = provinces.value[_pickerValue[0]]?.cityList || [];
    _pickerValue[1] = citys.value.findIndex(item => Number(item.citycode) === defaultValue.value[1]);
    // 设置区
    areas.value = citys.value[_pickerValue[1]]?.countyList || [];
    _pickerValue[2] = areas.value.findIndex(item => Number(item.countycode) === defaultValue.value[2]);

    // 重置下位置
    picker.value.setIndexs([_pickerValue[0], _pickerValue[1], _pickerValue[2]],true);
    userInfo.value.pickerValue = _pickerValue
}
const openChoose = () => {
    picker.value.open();
    handlePickValueDefault()
}
const confirmChange = (e : any) => {
    userInfo.value.provincecode = e.value[0].provincecode
    userInfo.value.citycode = e.value[1].citycode
    userInfo.value.countycode = e.value[2].countycode
    defaultValue.value = userInfo.value.pickerValue = [e.value[0].provincecode,e.value[1].citycode,e.value[2].countycode]
    pickerText.value = `${e.value[0].name}/${e.value[1].name}/${e.value[2].name}`
}

const submit = () => {
    const {address,citycode,countycode,mobile,defaultAddress,provincecode,realName,addressId} = userInfo.value
    if(!realName){
        uni.showToast({icon:'none',title:'收件人名不能为空'})
        return
    }
    if(!mobile){
        uni.showToast({icon:'none',title:'手机号码不能为空'})
        return
    }
    if(!address){
        uni.showToast({icon:'none',title:'详细地址不能为空'})
        return
    }
    if(!citycode || !countycode || !provincecode){
        uni.showToast({icon:'none',title:'城市不能为空'})
        return
    }
    
    saveAddress({
        address,citycode,countycode,mobile,defaultAddress,provincecode,realName,addressId
    }).then(res => {
        if(res.success){
            uni.showToast({icon:'success',title:'保存成功'})
            uni.navigateBack();
        }else uni.showToast({icon:'none',title:res.msg})
    })
}

onLoad(async (options) => {
	const { proxy } = getCurrentInstance();
    await proxy.$onLaunched;
    if(options.id && options.id != 'undefined')getAddress({addressId:options.id}).then(res => {
        userInfo.value = res.data
        const {provincecode,citycode,countycode,provincename,cityname,countyname} = res.data
        defaultValue.value = [provincecode,citycode,countycode]
        userInfo.value.pickerValue = [provincecode,citycode,countycode]
        userInfo.value.addressId = options.id
        pickerText.value = `${provincename}/${cityname}/${countyname}`
    })

    province({}).then(res => {
        res.data.forEach(province => {
            province.name = province.provincename
            if(province.cityList && province.cityList.length > 0){
                province.cityList.forEach(city => {
                    city.name = city.cityname
                    if(city.countyList && city.countyList.length > 0){
                        city.countyList.forEach(county => {
                            county.name = county.countyname
                        })
                    }
                })
            }
        })
        provinces.value = res.data
        handlePickValueDefault()
    })
})
</script>
<style>
.edit-address{
    padding: 16px;
    width: 100%;
    box-sizing: border-box;
    height: calc(100vh - 32px);
    position: relative;
}
.edit-address .uv-form{
    background: #fff;
    padding: 16px;
    border-radius: 9px;
}
.edit-address .uv-input{
    background: #fff !important;
    border: 0 !important;
    margin: 0 !important;
    padding:6px !important;
}
.edit-address .uv-input .uv-button-wrapper{margin: 0px !important}
</style>